<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="物料分析编码" prop="aomCode">
        <el-input
          v-model="queryParams.aomCode"
          placeholder="请输入物料分析编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料分析名称" prop="aomName">
        <el-input
          v-model="queryParams.aomName"
          placeholder="请输入物料分析名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分析日期" prop="params">
        <el-date-picker
          clearable
          v-model="queryParams.params"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          placeholder="请选择分析日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.aom_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pro:aom:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="aomList" @selection-change="handleSelectionChange">
      <el-table-column label="物料分析编码" align="center" prop="aomCode">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleInfoView(scope.row)">{{ scope.row.aomCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="物料分析名称" align="center" prop="aomName"/>
      <el-table-column label="分析日期" align="center" prop="aomDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.aomDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.aom_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产计划物料分析对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="optType == 'view'">
        <el-row>
          <el-col :span="8">
            <el-form-item label="物料分析编码" prop="aomCode">
              <el-input v-model="form.aomCode" placeholder="请输入物料分析编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)"
                v-if="optType != 'view' && optType != 'save'"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料分析名称" prop="aomName">
              <el-input v-model="form.aomName" placeholder="请输入物料分析名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划编号" prop="planCode">
              <el-input v-model="form.planCode" placeholder="请输入计划编号">
                <el-button slot="append" icon="el-icon-search" @click="handlePlanSelect"></el-button>
              </el-input>
            </el-form-item>
            <PlanningMulti ref="planSelect" @onSelected="onPlanSelected" :status="planStatus"></PlanningMulti>
          </el-col>
        </el-row>

      </el-form>
      <el-tabs type="border-card" v-if="planIds != null && planIds.length > 0">
        <el-tab-pane label="物料组成">
          <AnalysisBom ref="matlist" :planIds="this.planIds" :optType="optType" :aomId="form.id"></AnalysisBom>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="optType != 'view'">确 认</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addAom, getAom, listAom, updateAom } from "@/api/mes/pro/aom";
import PlanningMulti from "@/components/planSelect/multi.vue";
import AnalysisBom from "@/views/mes/pro/aom/bom/bom.vue";
import { genCode } from "@/api/system/autocode/rule";

export default {
  name: "Aom",
  components: {AnalysisBom, PlanningMulti},
  dicts: ['aom_status'],
  data() {
    return {
      //自动生成编号
      autoGenFlag: false,
      // 遮罩层
      loading: true,
      optType: undefined,
      planStatus: 'DAIFENJIE',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划物料分析表格数据
      aomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        aomCode: null,
        aomName: null,
        aomDate: null,
        status: null,
        params: [],

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        aomCode: [
          {required: true, message: "物料分析编码不能为空", trigger: "blur"}
        ],
        planCode: [
          {required: true, message: "计划编号不能为空", trigger: "blur"}
        ],
      },
      planIds: [],
      aomId: null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询生产计划物料分析列表 */
    getList() {
      this.loading = true;
      const query = { ...this.queryParams };
      if (query.params && query.params.length === 2) {
        query.params = {
          beginTime: query.params[0],
          endTime: query.params[1]
        };
      } else {
        query.params = null;
      }
      listAom(query).then(response => {
        this.aomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        aomCode: null,
        aomName: null,
        aomDate: null,
        planCode: null,
        status: "0",
      };
      this.planIds = [];
      this.autoGenFlag = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料分析";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAom(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料分析";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs[ "form" ].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //选择生产工单
    handlePlanSelect() {
      this.$refs.planSelect.showFlag = true;
    },
    onPlanSelected(row) {
      if (row != undefined && row != null) {
        this.planIds = [];
        this.form.planCode = "";
        this.form.planIds = "";
        row.forEach(item => {
          this.planIds.push(item.planId)
          this.form.planCode += item.planCode + ";";
          this.form.planIds += item.planId + ";";
        })
      }
    },
    // 查询明细按钮操作
    handleInfoView(row) {
      const id = row.id || this.ids;
      this.planIds = [];
      this.form.planCode = "";
      this.form.planIds = "";
      const uniquePlanIds = new Set();
      const uniquePlanCodes = new Set();
      getAom(id).then(response => {
        this.form = response.data;
        response.data.proPlanningAomLineList.forEach(item => {
          uniquePlanIds.add(item.planId);
          uniquePlanCodes.add(item.planCode);
        });
        this.form.planIds = Array.from(uniquePlanIds).join(';') + ';';
        this.form.planCode = Array.from(uniquePlanCodes).join(';') + ';';
        this.planIds = Array.from(uniquePlanIds);
        this.open = true;
        this.title = '查看物料分析';
        this.optType = 'view';
      });
    },

    //自动生成编号
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('AOM_CODE').then(response => {
          this.form.aomCode = response;
        });
      } else {
        this.form.aomCode = null;
      }
    },
  }
};
</script>
<style>
.warning-row {
  background-color: oldlace !important;
}
</style>
